<template>
  <div class="distributor-list">
    <div class="distributor-list__header">
      <h1>分销商列表</h1>
      <div class="distributor-list__actions">
        <div class="search-box">
          <input 
            type="text" 
            v-model="searchQuery" 
            placeholder="搜索分销商名称或ID"
            @input="handleSearch"
          />
          <i class="fas fa-search"></i>
        </div>
        
        <div class="filter-group">
          <select v-model="statusFilter" @change="applyFilters">
            <option value="">全部状态</option>
            <option value="active">活跃</option>
            <option value="pending">待审核</option>
            <option value="inactive">已禁用</option>
          </select>
        </div>
        
        <button class="add-btn" @click="handleAddDistributor">
          <i class="fas fa-plus"></i> 添加分销商
        </button>
      </div>
    </div>
    
    <div v-if="loading" class="loading-state">
      <div class="spinner"></div>
      <p>加载中，请稍候...</p>
    </div>
    
    <div v-else-if="filteredDistributors.length === 0" class="empty-state">
      <i class="far fa-sad-tear"></i>
      <p>未找到符合条件的分销商</p>
      <button class="reset-btn" @click="resetFilters">重置筛选条件</button>
    </div>
    
    <div v-else class="distributor-grid">
      <DistributorCard 
        v-for="distributor in filteredDistributors" 
        :key="distributor.id"
        :distributor="distributor"
        @view="handleViewDistributor"
        @edit="handleEditDistributor"
        @toggle-status="handleToggleStatus"
      />
    </div>
    
    <div class="pagination">
      <button 
        class="page-btn prev" 
        :disabled="currentPage === 1" 
        @click="handlePageChange(currentPage - 1)"
      >
        <i class="fas fa-chevron-left"></i> 上一页
      </button>
      
      <span class="page-info">第{{ currentPage }}/{{ totalPages }}页</span>
      
      <button 
        class="page-btn next" 
        :disabled="currentPage === totalPages" 
        @click="handlePageChange(currentPage + 1)"
      >
        下一页 <i class="fas fa-chevron-right"></i>
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import DistributorCard from '@/components/agent/distributors/DistributorCard.vue';
import { generateDistributorsData } from '@/utils/agentMock';

// 状态
const loading = ref(true);
const distributors = ref<any[]>([]);
const searchQuery = ref('');
const statusFilter = ref('');
const currentPage = ref(1);
const pageSize = ref(9); // 每页显示9个卡片，适合3x3网格

// 加载数据
const fetchData = () => {
  loading.value = true;
  
  // 模拟API请求延迟
  setTimeout(() => {
    // 生成模拟数据
    distributors.value = generateDistributorsData(30); // 生成更多数据供分页使用
    loading.value = false;
  }, 800);
};

// 计算所有过滤后的数据（用于计算总页数）
const allFilteredDistributors = computed(() => {
  let result = [...distributors.value];
  
  // 按名称或ID搜索
  if (searchQuery.value) {
    const keyword = searchQuery.value.toLowerCase();
    result = result.filter(item => 
      item.name.toLowerCase().includes(keyword) || 
      item.id.toLowerCase().includes(keyword)
    );
  }
  
  // 按状态筛选
  if (statusFilter.value) {
    result = result.filter(item => item.status === statusFilter.value);
  }
  
  return result;
});

// 筛选分销商数据（当前页显示的数据）
const filteredDistributors = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;
  return allFilteredDistributors.value.slice(startIndex, endIndex);
});

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(allFilteredDistributors.value.length / pageSize.value) || 1;
});

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1; // 重置到第一页
};

// 应用筛选
const applyFilters = () => {
  currentPage.value = 1; // 重置到第一页
};

// 重置筛选条件
const resetFilters = () => {
  searchQuery.value = '';
  statusFilter.value = '';
  currentPage.value = 1;
};

// 处理页码变化
const handlePageChange = (page: number) => {
  currentPage.value = page;
};

// 处理添加分销商
const handleAddDistributor = () => {
  alert('添加分销商功能将在后续实现');
};

// 处理查看分销商详情
const handleViewDistributor = (distributor: any) => {
  console.log('查看分销商详情:', distributor);
  // 实际项目中会导航到详情页或显示详情弹窗
  alert(`查看分销商: ${distributor.name}`);
};

// 处理编辑分销商
const handleEditDistributor = (distributor: any) => {
  console.log('编辑分销商:', distributor);
  // 实际项目中会导航到编辑页或显示编辑弹窗
  alert(`编辑分销商: ${distributor.name}`);
};

// 处理启用/禁用分销商
const handleToggleStatus = (distributor: any) => {
  console.log('切换分销商状态:', distributor);
  
  // 在当前数据中查找并更新状态
  const index = distributors.value.findIndex(item => item.id === distributor.id);
  if (index !== -1) {
    const newStatus = distributor.status === 'inactive' ? 'active' : 'inactive';
    distributors.value[index].status = newStatus;
    alert(`${newStatus === 'active' ? '启用' : '禁用'}分销商: ${distributor.name}`);
  }
};

// 生命周期钩子
onMounted(() => {
  fetchData();
});
</script>

<style lang="scss" scoped>
.distributor-list {
  padding: 24px;
  
  &__header {
    margin-bottom: 24px;
    
    h1 {
      font-size: 24px;
      font-weight: 600;
      color: #2f3542;
      margin: 0 0 16px 0;
    }
  }
  
  &__actions {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    align-items: center;
  }
  
  .search-box {
    position: relative;
    flex: 1;
    min-width: 200px;
    
    input {
      width: 100%;
      padding: 10px 16px;
      padding-right: 40px;
      border-radius: 8px;
      border: 1px solid #dee2e6;
      font-size: 14px;
      transition: all 0.2s;
      
      &:focus {
        outline: none;
        border-color: #4a6cf7;
        box-shadow: 0 0 0 2px rgba(74, 108, 247, 0.15);
      }
    }
    
    i {
      position: absolute;
      right: 16px;
      top: 50%;
      transform: translateY(-50%);
      color: #6c757d;
    }
  }
  
  .filter-group {
    min-width: 150px;
    
    select {
      width: 100%;
      padding: 10px 16px;
      border-radius: 8px;
      border: 1px solid #dee2e6;
      font-size: 14px;
      background-color: #fff;
      cursor: pointer;
      appearance: none;
      -webkit-appearance: none;
      -moz-appearance: none;
      background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%236c757d'%3E%3Cpath d='M7 10l5 5 5-5z'/%3E%3C/svg%3E");
      background-repeat: no-repeat;
      background-position: right 12px center;
      background-size: 16px;
      transition: all 0.2s;
      
      &:focus {
        outline: none;
        border-color: #4a6cf7;
        box-shadow: 0 0 0 2px rgba(74, 108, 247, 0.15);
      }
    }
  }
  
  .add-btn {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 10px 20px;
    background-color: #4a6cf7;
    color: white;
    border: none;
    border-radius: 8px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    
    &:hover {
      background-color: darken(#4a6cf7, 5%);
    }
    
    &:active {
      transform: translateY(1px);
    }
  }
  
  .distributor-grid {
    display: grid;
    gap: 24px;
    margin-bottom: 24px;
    
    // 响应式网格:
    // 大屏幕 (1200px以上): 每行3个卡片
    // 中等屏幕 (992px-1199px): 每行2个卡片
    // 小屏幕 (768px以下): 每行1个卡片
    grid-template-columns: 1fr;
    
    @media (min-width: 768px) {
      grid-template-columns: repeat(2, 1fr);
    }
    
    @media (min-width: 1200px) {
      grid-template-columns: repeat(3, 1fr);
    }
  }
  
  .loading-state, .empty-state {
    padding: 60px 20px;
    text-align: center;
    color: #6c757d;
    
    i {
      font-size: 48px;
      margin-bottom: 16px;
    }
    
    p {
      font-size: 16px;
      margin-bottom: 16px;
    }
    
    .spinner {
      display: inline-block;
      width: 48px;
      height: 48px;
      border: 4px solid rgba(74, 108, 247, 0.2);
      border-radius: 50%;
      border-top-color: #4a6cf7;
      animation: spin 1s linear infinite;
      margin-bottom: 16px;
    }
    
    .reset-btn {
      padding: 8px 20px;
      background-color: #e9ecef;
      border: none;
      border-radius: 8px;
      font-size: 14px;
      cursor: pointer;
      transition: all 0.2s;
      
      &:hover {
        background-color: darken(#e9ecef, 5%);
      }
    }
  }
  
  .pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 20px;
    margin-top: 24px;
    
    .page-btn {
      padding: 8px 16px;
      background-color: #f8f9fa;
      border: 1px solid #dee2e6;
      border-radius: 8px;
      font-size: 14px;
      cursor: pointer;
      transition: all 0.2s;
      display: flex;
      align-items: center;
      gap: 6px;
      
      &:hover:not(:disabled) {
        background-color: darken(#f8f9fa, 5%);
      }
      
      &:disabled {
        opacity: 0.5;
        cursor: not-allowed;
      }
    }
    
    .page-info {
      font-size: 14px;
      color: #6c757d;
    }
  }
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

@media (max-width: 768px) {
  .distributor-list {
    padding: 16px;
    
    &__actions {
      flex-direction: column;
      align-items: stretch;
    }
  }
}
</style> 